package com.taptech.doufu.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.common.UiError;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.SdkListener;
import com.sina.weibo.sdk.openapi.WBAPIFactory;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.CommentDataBean;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.UGCMainService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.FetchResourceUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.UIUtil;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class SinaWeiboActivity extends DiaobaoBaseActivity implements HttpResponseListener,WbShareCallback {
    private String shareWeiboText = "";
    private String imgPath = "";
    private int flag;
    private ImageView showShareImg;

    private Boolean isImgPaht = false;
    Bitmap bmp = null;

    /**
     * 微博微博分享接口实例
     */
    private ShareBeansInfo beansInfo;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_weibo);
//        if (isWeiboInstall(this)) {
//
//        }else{
//            Toast.makeText(this,"请安装微博客户端后再分享",Toast.LENGTH_LONG).show();
//            finish();
//            DiaobaoBaseActivity.exitAnimAlpha(this);
//        }
        initWeiboSdk();
        creatUi();
    }


    private IWBAPI mWBAPI;
    private void initWeiboSdk() {
        AuthInfo authInfo = new AuthInfo(this, Constant.APP_KEY, Constant.REDIRECT_URL, WeiboService.SCOPE);
        mWBAPI = WBAPIFactory.createWBAPI(this);
        mWBAPI.registerApp(this, authInfo, new SdkListener() {
            @Override
            public void onInitSuccess() {
                // SDK初始化成功回调，成功⼀次后再次初始化将不再有任何回调
            }

            @Override
            public void onInitFailure(Exception e) {
                // SDK初始化失败回调
            }
        });
    }

    /**
     * 检查是否安装微博
     * @param context
     * @return
     */
    public static boolean isWeiboInstall(Context context) {
//        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
//        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
//        if (pinfo != null) {
//            for (int i = 0; i < pinfo.size(); i++) {
//                String pn = pinfo.get(i).packageName;
//                if (pn.equals("com.sina.weibo")) {
//                    return true;
//                }
//            }
//        }

        return false;
    }
    public void creatUi() {
        try {
            showShareImg = (ImageView) findViewById(R.id.iv_weibo_sharephoto);

            Intent intent = getIntent();
            TTLog.d("tag", "beanInfo share flag ==================" + intent.toString());
            if (intent != null) {

                flag = intent.getIntExtra("flag", 0);
                TTLog.d("tag", "beanInfo share flag ==================" + flag);
                beansInfo = (ShareBeansInfo) intent
                        .getSerializableExtra("shareInfo");
                switch (flag) {
                    case ShareBeansInfo.AETICLE_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        imgPath = ImageManager.getCacheFilePath(beansInfo
                                .getImagUrl());
                        isImgPaht = true;
                        break;
                    case ShareBeansInfo.OWN_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        break;
                    case ShareBeansInfo.PHOTO_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        imgPath = ImageManager.getCacheFilePath(beansInfo
                                .getImagUrl());
                        isImgPaht = true;
                        break;
                    case ShareBeansInfo.WOED_SHARE_FlAG:
                        shareWeiboText = beansInfo.getShartText();
                        break;
                    case ShareBeansInfo.VIDEO_SHARE_FLAG:

                        shareWeiboText = beansInfo.getShartText();
                        if (beansInfo.getShareData() != null) {
                            imgPath = beansInfo.getShareData().getShareUrl();
                        } else {
                            imgPath = beansInfo.getShareUrl();
                        }
                        if (imgPath == null) {
                            imgPath = Constant.DOWN_URL_WB;
                        }
                        break;
                    case ShareBeansInfo.TOPIC_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        TTLog.s("beansInfo.getImagUrl()==" + beansInfo.getImagUrl());
                        isImgPaht = beansInfo.getImagUrl() != null;
                        if (isImgPaht) {
                            imgPath = ImageManager.getCacheFilePath(beansInfo
                                    .getImagUrl());
                        }

                        break;
                    case ShareBeansInfo.NOVEL_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        isImgPaht = beansInfo.getImagUrl() != null;
                        if (isImgPaht) {
                            String url = Constant.LOGO_URL;
                            if (!TextUtils.isEmpty(beansInfo.getImagUrl())) {
                                url = beansInfo.getImagUrl();
                            }
                            url = Constant.changeUrlHost(url);
                            Glide.with(WeMediaApplication.applicationContext).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap logoBitmap, @Nullable Transition<? super Bitmap> transition) {
                                    imgPath = ImageManager.getCacheFilePath(beansInfo
                                            .getImagUrl());
                                    if (logoBitmap == null) {
                                        logoBitmap = FetchResourceUtil.fetchBitmap(getResources(),
                                                R.drawable.new_icon);
                                    }
                                    showShareImg.setImageBitmap(logoBitmap);
                                    // 创建微博分享接口实例
                                    sendMessage(isImgPaht);
                                }

                            });
                            return;
                        }
                        break;
                    case ShareBeansInfo.SWEEP_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        break;
                    case ShareBeansInfo.RANK_SORCE_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        break;
                    case ShareBeansInfo.NOTE_SHARE_FLAG:
                        shareWeiboText = beansInfo.getShartText();
                        TTLog.d("tag", "beanInfo share image is==============" + beansInfo.getImagUrl());
                        isImgPaht = beansInfo.getImagUrl() != null;
                        if (isImgPaht) {
                            imgPath = ImageManager.getCacheFilePath(beansInfo
                                    .getImagUrl());
                        }
                        break;
                    default:
                        shareWeiboText = beansInfo.getShartText();
                        break;
                }

                if (isImgPaht && flag != 5) {
                    bmp = ImageManager.getCacheBitMap(beansInfo.getImagUrl());
                    if (bmp == null) {
                        bmp = FetchResourceUtil.fetchBitmap(getResources(),
                                R.drawable.new_icon);
                    }
                    showShareImg.setImageBitmap(bmp);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建微博分享接口实例
        sendMessage(isImgPaht);


    }


    public static void shareToWeibo(Context mContext,ShareBeansInfo shareInfo) {
        Intent intent = new Intent(mContext, SinaWeiboActivity.class);
        if (shareInfo == null) {
            Toast.makeText(mContext, "分享失败", Toast.LENGTH_LONG).show();
            return;
        }
        intent.putExtra("flag", shareInfo.getFlag());
        intent.putExtra("shareInfo", shareInfo);
        mContext.startActivity(intent);
    }

    /**
     * @see {@link Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (handleType == UGCMainService.HANDLE_TYPE_LOAD_SHARE_SCORE) {
            try {
                if (response.getStatus() == 0) {
                    UIUtil.dismissDialog();
                    CommentDataBean scrore = new CommentDataBean();
                    scrore.setJson(((JSONObject) response.getData()).getJSONObject("score_result"));
                    int commentScore = Integer.valueOf(scrore.getScore());
                    if (commentScore != 0) {
                        UIUtil.toastMessage(SinaWeiboActivity.this, "分享成“攻” +5豆子");
                    } else {
                        UIUtil.toastMessage(SinaWeiboActivity.this, "分享成“攻”" + Constant.REPLY_TODAY_FULL);
                    }
                    //回调，给后台数据
                    setResult(666, getIntent());
                } else {
                    UIUtil.toastMessage(SinaWeiboActivity.this, DiaobaoUtil.getErrorTips(response));
                }
                finish();
                DiaobaoBaseActivity.exitAnimAlpha(this);
            } catch (JSONException e) {
                e.printStackTrace();
                finish();
                DiaobaoBaseActivity.exitAnimAlpha(this);
            }

        } else {
            if (response.getStatus() == 0) {
                UIUtil.toastMessage(this, "授权成功");
                mHandler.sendEmptyMessage(NEW_WEIBO_SHARE);
            } else {
                UIUtil.toastMessage(this, DiaobaoUtil.getErrorTips(response));
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mWBAPI != null) {
            mWBAPI.doResultIntent(data, this);
        }
    }



    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 0:
                    UIUtil.toastMessage(getApplicationContext(), "发送微博失败");
                    break;
                case 1:
                    //分享统计
                    UGCMainService.getInstance().uploadShareScore(beansInfo.getId(),
                            String.valueOf(beansInfo.getSocial_type()), beansInfo.getShareData().getObject_type(), SinaWeiboActivity.this);
                    break;
                default:
                    break;
            }

        }

        ;
    };

    private final int NEW_WEIBO_SHARE = 999;



    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。

     */
    private void sendMessage(boolean hasImage) {
        sendMultiMessage(hasImage);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     * 同时可以分享文本、图片以及其它媒体资源（网页、音乐、视频、声音中的一种）。
     *
     * @param hasImage   分享的内容是否有图片
     */
    private void sendMultiMessage(boolean hasImage) {

        try {
            // 1. 初始化微博的分享消息
            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            if (beansInfo!=null && beansInfo.getDataType() != Constant.ShareDataType.SHARE_DATA_TYPE_IMAGE) {
                weiboMessage.textObject = getTextObj();
            }
            if (hasImage) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) showShareImg.getDrawable();
                if (bitmapDrawable != null) {
                    // 分享图⽚
                    ImageObject imageObject = new ImageObject();
                    imageObject.setImageData(bitmapDrawable.getBitmap());
                    weiboMessage.imageObject = imageObject;
                }
            }
            mWBAPI.shareMessage(this, weiboMessage, true);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,"分享失败，请重试",Toast.LENGTH_LONG).show();
            finish();
        }
    }




    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = shareWeiboText;
        return textObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onComplete() {
        //分享统计
        if (beansInfo!=null && beansInfo.isForWeex()) {
//            NotifyUtil.shareNotify("分享成功");
            Toast.makeText(this,"分享成功",Toast.LENGTH_LONG).show();
            finish();
            DiaobaoBaseActivity.exitAnimAlpha(this);

        }else{
            if (beansInfo!=null && beansInfo.getId() != null ) {
                String objectType = beansInfo.getObject_type();
                if (beansInfo.getShareData() != null && !TextUtils.isEmpty(beansInfo.getShareData().getObject_type())) {
                    objectType = beansInfo.getShareData().getObject_type();
                }
                HomeMainServices.getInstance().getShareUrlRequest(beansInfo.getId(), objectType,null,beansInfo.shareUrl);
                UGCMainService.getInstance().uploadShareScore(beansInfo.getId(),
                        String.valueOf(beansInfo.getSocial_type()), objectType, SinaWeiboActivity.this);
            } else {
                finish();
                DiaobaoBaseActivity.exitAnimAlpha(this);
            }
        }
    }

    @Override
    public void onError(UiError uiError) {
        if (beansInfo!=null && beansInfo.isForWeex()) {
            Toast.makeText(this,"分享失败",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(SinaWeiboActivity.this,
                    getString(R.string.weibosdk_demo_toast_share_failed)  ,
                    Toast.LENGTH_LONG).show();
        }
        finish();
        DiaobaoBaseActivity.exitAnimAlpha(this);
    }

    @Override
    public void onCancel() {
        if (beansInfo!=null && beansInfo.isForWeex()) {
            Toast.makeText(this,"分享取消",Toast.LENGTH_LONG).show();

        }else{
            Toast.makeText(SinaWeiboActivity.this, R.string.weibosdk_demo_toast_share_canceled, Toast.LENGTH_LONG).show();
        }
        finish();
        DiaobaoBaseActivity.exitAnimAlpha(this);
    }
}